package leetcode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Stream;

public class Lc1336 {

    public String rankTeams(String[] votes) {

        if (votes.length == 1)
            return votes[0];
        HashMap<Character, Team> map = new HashMap<>();

        for (int i = 0; i < votes.length; i++) {
            char[] vote = votes[i].toCharArray();
            for (int j = 0; j < vote.length; j++) {
                Team team = map.getOrDefault(vote[j], new Team(vote[j], vote.length));
                team.rank[j] ++;
                map.put(vote[j], team);
            }
        }
        ArrayList<Team> teamList = new ArrayList<>(map.values());
        Collections.sort(teamList);
        StringBuffer buff = new StringBuffer();
        for (int i = 0; i < teamList.size(); i++) {
            buff.append(teamList.get(i).name);
        }
        return buff.toString();
    }

//    public static void main(String[] args) {
//        Lc1336 lc1336 = new Lc1336();
//        String[] s = {"WXYZ","XYZW"};
//        System.out.printf(lc1336.rankTeams(s));
//    }
}

class Team implements Comparable<Team>{
    public Character name;
    public int[] rank;

    public Team(Character name, int len) {
        this.name = name;
        rank = new int[len];
    }

    @Override
    public int compareTo(Team t) {
        int idx = 0;
        while (idx < rank.length) {
            if (this.rank[idx] != t.rank[idx]) {
                return -(this.rank[idx] - t.rank[idx]);
            }
            idx ++;
        }
        return this.name.compareTo(t.name);
    }
}